#import "UIView+YLWebCacheOperation.h"
#import "objc/runtime.h"
#import "YLWebImageOperation.h"

static char loadOperationKey;

typedef NSMapTable<NSString *, id<YLWebImageOperation>> YLOperationsDictionary;

@implementation UIView (YLWebCacheOperation)

- (YLOperationsDictionary *)yl_operationDictionary {
    @synchronized(self) {
        YLOperationsDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey);
        if (operations) {
            return operations;
        }
        operations = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:0];
        objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        return operations;
    }
}

- (void)yl_setImageLoadOperation:(nullable id<YLWebImageOperation>)operation forKey:(nullable NSString *)key {
    if (key) {
        [self yl_cancelImageLoadOperationWithKey:key];
        if (operation) {
            YLOperationsDictionary *operationDictionary = [self yl_operationDictionary];
            @synchronized (self) {
                [operationDictionary setObject:operation forKey:key];
            }
        }
    }
}

- (void)yl_cancelImageLoadOperationWithKey:(nullable NSString *)key {
    if (key) {
        // Cancel in progress downloader from queue
        YLOperationsDictionary *operationDictionary = [self yl_operationDictionary];
        id<YLWebImageOperation> operation;
        
        @synchronized (self) {
            operation = [operationDictionary objectForKey:key];
        }
        if (operation) {
            if ([operation conformsToProtocol:@protocol(YLWebImageOperation)]) {
                [operation cancel];
            }
            @synchronized (self) {
                [operationDictionary removeObjectForKey:key];
            }
        }
    }
}

- (void)yl_removeImageLoadOperationWithKey:(nullable NSString *)key {
    if (key) {
        YLOperationsDictionary *operationDictionary = [self yl_operationDictionary];
        @synchronized (self) {
            [operationDictionary removeObjectForKey:key];
        }
    }
}

@end
